# troop_card.gd
extends PanelContainer
class_name TroopCard

# 自定义信号：当请求兵力调整时触发（delta: 当前量, card: 当前卡片实例）
signal amount_requested(delta: int, card: TroopCard)

# 属性
var troop_type: int = -1 ## 兵种类型标识（需与数据表对应）
var icon_path: String = "" ## 图标路径（需以res://开头的有效资源路径）
var scene_path: String = ""
var current_count := 0

# 节点引用
@onready var texture_rect: TextureRect = $VBoxContainer/TextureRect ## 兵种图标显示区域
@onready var count_label: Label = $VBoxContainer/HBoxContainer/Count ## 数量显示标签
@onready var buttons = { ## 操作按钮集合
	"minus_10": $VBoxContainer/HBoxContainer/DecreaseTen,
	"minus_1": $VBoxContainer/HBoxContainer/DecreaseOne,
	"add_1": $VBoxContainer/HBoxContainer/AddOne,
	"add_10": $VBoxContainer/HBoxContainer/AddTen
}


#region 生命周期方法
func _ready() -> void:
	"""初始化组件：连接按钮信号，加载初始图标"""
	# 连接按钮信号
	_connect_button_signals()
	# 加载初始图标
	if not icon_path.is_empty():
		update_icon(icon_path)

#endregion

#region 公共方法
func update_display(current: int = 0, max_available: int = 0) -> void:
	"""
	更新界面显示状态
	@param current: 当前兵力数量
	@param max_available: 最大可用兵力
	"""
	current_count = current
	count_label.text = str(current)
	_update_buttons_state(current, max_available)

func update_icon(new_path: String) -> void:
	"""
	动态更新兵种图标
	@param new_path: 新图标路径（需以res://开头）
	@warning: 无效路径会触发警告但不会中断运行
	"""
	icon_path = new_path
	
	if icon_path.is_empty():
		push_warning("图标路径不能为空")
		return
		
	if ResourceLoader.exists(icon_path):
		texture_rect.texture = load(icon_path)
	else:
		push_warning("图标加载失败: %s (文件不存在或格式不支持)" % icon_path)
	
	queue_redraw()

#endregion

#region 私有方法
func _connect_button_signals() -> void:
	"""连接所有按钮的按下信号到统一处理方法"""
	buttons["minus_10"].pressed.connect(_emit_change.bind(-10))
	buttons["minus_1"].pressed.connect(_emit_change.bind(-1))
	buttons["add_1"].pressed.connect(_emit_change.bind(1))
	buttons["add_10"].pressed.connect(_emit_change.bind(10))

func _update_buttons_state(current: int, max_available: int) -> void:
	"""更新按钮的禁用状态"""
	buttons["minus_10"].disabled = current < 10
	buttons["minus_1"].disabled = current < 1
	buttons["add_1"].disabled = current >= max_available
	buttons["add_10"].disabled = (current + 10) > max_available

func _emit_change(delta: int) -> void:
	"""处理按钮点击事件并发射信号"""
	amount_requested.emit(delta, self)

#endregion
